import { Component, OnInit, HostBinding, ChangeDetectorRef } from '@angular/core';
import { FormBuilder, Validators } from '@angular/forms';
import { LoginService } from '../services/login.service';
import { NgxPermissionsService } from 'ngx-permissions';
import { Router } from '@angular/router';
import { HttpErrorResponse } from '@angular/common/http';
import { MatDialog } from '@angular/material';
import { markAllAsTouched, confirmPassword } from 'app/modules/base/helper';
import { ToasterService } from 'app/modules/share/services/toaster.service';
import { ProfileService } from 'app/services/profile.service';
import { Buffer } from 'buffer';

@Component({
  selector: 'm-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.scss'],
})
export class LoginComponent implements OnInit {
  constructor(
    private router: Router,
    public dialog: MatDialog,
    private fb: FormBuilder,
    private toaster: ToasterService,
    private cd: ChangeDetectorRef,
    private permissionsService: NgxPermissionsService,
    private loginService: LoginService,
    private profileService: ProfileService,
  ) {}
  @HostBinding('class') classList = 'm-grid m-grid--hor m-grid--root m-page ng-star-inserted';

  profile$ = this.profileService.profile$;
  form = this.fb.group({
    username: ['', Validators.required],
    password: ['', Validators.required],
  });
  resetForm = this.fb.group(
    {
      token: ['', Validators.required],
      password: ['', Validators.required],
      confirm: ['', Validators.required],
    },
    { validators: confirmPassword() },
  );
  ngOnInit() { }

  async login() {
    markAllAsTouched(this.form);
    if (this.form.invalid) {
      return;
    }
    let password: string = '';
    let str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    for (var i = 0; i < 8; i++) {
      var rand = Math.floor(Math.random() * str.length);
      password += str.charAt(rand);
    }
    password = new Buffer(this.form.value.password).toString('base64') + password;
    this.form.value.password = password;
    try {
      await this.loginService.Login(this.form.value);
      const user = await this.loginService.User();
      if (user.logged) {
        this.permissionsService.loadPermissions(['USER', 'ADMIN']);
        this.router.navigate(['/']);
      }
    } catch (err) {
      if (err instanceof HttpErrorResponse) {
        switch (err.status) {
          case 401:
            this.form.setErrors({ auth: true });
            break;
          case 423:
            this.form.setErrors({ locked: true });
            break;
          default:
            this.form.setErrors({ error: true });
        }
      }
    }
    this.cd.detectChanges();
  }

  async reset() {
    markAllAsTouched(this.resetForm);
    if (this.resetForm.invalid) {
      return;
    }
    const value = this.resetForm.value;
    const data = {
      reset_token: value.token,
      new_password: value.password,
    };
    try {
      await this.loginService.reset(data);
      this.dialog.closeAll();
      this.toaster.success('重置密码成功');
    } catch (err) {
      if (err instanceof HttpErrorResponse) {
        if (err.status === 401) {
          this.resetForm.get('token').setErrors({ token: true });
        }
      }
    }
  }
}
